package com.my.code.samphore;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * Semaphore测试
 */
public class SemaphoreDemo {
    static final int SIZE = 5;

    public static void main(String[] args) throws Exception {
        final Pool<Fat> pool = new Pool<>(SIZE, Fat.class);
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < SIZE; i++) {
            exec.execute(new CheckTask<>(pool));
        }
        System.out.println("All CheckOutTask Created");
        ArrayList<Fat> fats = new ArrayList<>();
        for (int i = 0; i < SIZE; i++) {
            Fat fat = pool.checkOut();
            System.out.println("main thread checked out " + i);
            fat.operation();
            fats.add(fat);
        }

        Future<?> blocked = exec.submit(() -> {
            try {
                pool.checkOut();//call is blocked here
            } catch (InterruptedException e) {
                System.out.println("\ncheck out interrupted !");
            }
        });

        TimeUnit.SECONDS.sleep(2);
        blocked.cancel(true);//break block
        System.out.println("main fats.size=" + fats.size());
        System.out.println("\nfirst main check in loop...");
        for (Fat fat : fats) {
            pool.checkIn(fat);
        }
        System.out.println("\nsecond main check in loop...");
        for (Fat fat : fats) {
            pool.checkIn(fat);
        }
        exec.shutdown();
    }

}
